<template>
  <div class="login-page relative">
    <img
      v-if="$config.ShowLogo"
      src="@/assets/logo_l.png"
      class="mt-5 ml-5"
      style="width: 140px"
    />
    <div class="login-container absolute">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <!-- <img class="img" src="@/assets/login/illustration.png" alt="" /> -->
      <div class="login-form bg-white pr-8 pl-8 pb-12">
        <Motion>
          <h2
            class="outline-none text-center pt-12 font-normal mb-8 border-box"
          >
            用户登录
          </h2>
        </Motion>

        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="loginRules"
          size="large"
        >
          <Motion :delay="100">
            <el-form-item
              :rules="[
                {
                  required: true,
                  message: '请输入账号',
                  trigger: 'blur'
                }
              ]"
              prop="username"
            >
              <el-input
                v-model="ruleForm.username"
                clearable
                placeholder="账号"
                :prefix-icon="useRenderIcon(User)"
              />
            </el-form-item>
          </Motion>

          <Motion :delay="150">
            <el-form-item prop="password">
              <el-input
                v-model="ruleForm.password"
                clearable
                show-password
                placeholder="密码"
                :prefix-icon="useRenderIcon(Lock)"
              />
            </el-form-item>
          </Motion>

          <Motion :delay="250">
            <el-button
              class="w-full mt-4"
              type="primary"
              :loading="loading"
              @click="onLogin(ruleFormRef)"
            >
              登录
            </el-button>
          </Motion>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter, useRoute } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  ref,
  reactive,
  toRaw,
  onMounted,
  onBeforeUnmount,
  getCurrentInstance
} from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import illustration from "@/assets/login/illustration.svg?component";

import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";

// import { localForage } from "@/utils/localforage";
import { storageLocal } from "@pureadmin/utils";
const $config = getCurrentInstance().appContext.config.globalProperties.$config;

defineOptions({
  name: "Login"
});
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title } = useNav();

const ruleForm = reactive({
  username: "",
  password: ""
});
if (storageLocal().getItem("LoginUserName")) {
  ruleForm.username = storageLocal().getItem("LoginUserName");
}

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      useUserStoreHook()
        .loginByUsername({
          username: ruleForm.username,
          password: ruleForm.password,
          grantType: "password",
          clientId: "e5cd7e4891bf95d1d19206ce24a7b32e"
        })
        .then(res => {
          if (res.code === 200) {
            // 获取后端路由
            return initRouter().then(() => {
              storageLocal().setItem("LoginUserName", ruleForm.username);
              if (route?.query?.repage) {
                router.push({ name: String(route.query.repage) }).then(() => {
                  message("登录成功", { type: "success" });
                });
                return;
              }
              router.push(getTopMenu(true).path).then(() => {
                message("登录成功", { type: "success" });
              });
            });
          } else {
            message("登录失败", { type: "error" });
          }
        })
        .finally(() => (loading.value = false));
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (["Enter", "NumpadEnter"].includes(code)) {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  useUserStoreHook().logOut(false, false);
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.login-page {
  width: 100vw;
  height: 100vh;
  background: url("@/assets/svg/login_bg.svg") no-repeat left bottom;
  background-size: contain;
  background-color: #eaf0fc;
  .login-container {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    width: 100%;
    justify-content: center;
    .img {
      width: 420px;
    }
  }
}
.login-form {
  width: 360px;
  h2 {
    font-size: 28px;
    &::after {
      content: "";
      display: block;
      width: 10%;
      height: 4px;
      background: #3e7dff;
      border-radius: 5px;
      margin: 0 auto;
    }
  }
}

@media screen and (max-width: 1180px) {
  .login-form {
    width: 290px;
  }

  .img {
    width: 360px;
  }
}

@media screen and (max-width: 968px) {
  .img {
    display: none;
  }
}
</style>
